<template>
  <div class="upladingfies">
    <!-- 头部 -->
    <van-nav-bar title="修改头像" right-text="保存" @click-right="onClickRight">
      <template #left>
        <van-icon @click="$router.go(-1)" name="arrow-left" />
      </template>
    </van-nav-bar>
    <!-- 显示头像 -->
    <van-uploader v-model="fileList" multiple :after-read="afterRead" />
  </div>
</template>
<script>
// 导入Vuex中的数据
import { mapState, mapActions } from 'vuex'
// 导入 修改个人信息
import { photoes, edit } from '@/api/my.js'
import { Toast } from 'vant'
import { setLocal } from '@/utils/local.js'
export default {
  computed: {
    ...mapState({
      userInfo: state => state.userInfo
    })
  },
  // 从页面加载就执行
  created () {
    this.fileList = [
      {
        url: this.baseUrl + this.userInfo.avatar
      }
    ]
  },
  data () {
    return {
      fileList: [],
      // 基地址userInfo
      baseUrl: process.env.VUE_APP_URL,
      avatar: ''
    }
  },
  methods: {
    ...mapActions(['setUserInfo']),
    // 点击确认更换头像
    async afterRead (file) {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 20000
      })
      try {
        var img = file.file
        var res = await photoes(img)
        // 将服务器返回的数据赋值 fileList
        this.avatar = res.data[0].id
        this.userInfo.avatar = res.data[0].url
        // 提示用户
        this.$toast.success('成功上传头像')
      } catch {
        Toast.fail('上传头像失败')
      }
    },
    // 保存头像
    async onClickRight () {
      Toast.loading({
        message: '加载中...',
        forbidClick: true,
        duration: 20000
      })
      await edit({ avatar: this.avatar })
      setLocal(this.userInfo, 'userInfo')
      this.$toast.success('成功上传头像')
      this.$router.push('/user')
    }
  }
}
</script>

<style lang="less" scoped>
.upladingfies {
  position: relative;
  .print {
    width: 200px;
    height: 200px;
  }
  /deep/.van-uploader__upload,
  /deep/.van-uploader__file {
    position: absolute;
    width: 200px;
    height: 200px;
    margin-left: 90px;
    background-color: #f7f8fa;
  }
  /deep/.van-uploader__preview-image {
    // position: absolute;
    width: 200px;
    height: 200px;
    top: 15px;
    margin-left: 90px;
    overflow: hidden;
    z-index: 1;
  }
  /deep/.van-uploader__preview-delete {
    position: absolute;
    top: 7px;
    right: -5px;
    width: 18px;
    height: 18px;
    background-color: #969798;
    color: #969799;
    border-radius: 50px;
    z-index: 2;
  }
  .van-icon-clear:before {
    content: '\F031';
  }
  /deep/.van-icon-cross::before {
    font-size: 20px;
    margin: 2px 0 0 6px;
  }
  /deep/.van-nav-bar__title,
  /deep/.van-nav-bar__text {
    font-size: 16px;
    color: #fff;
  }
  /deep/.van-icon-arrow-left::before {
    color: #fff;
    font-size: 20px;
  }
  /deep/.van-nav-bar {
    background-color: red;
  }
}
</style>
